<template>
  <VideoPlayer
    :currentEpisodeIndex="currentEpisodeIndex"
    :current-video="currentVideo"
    episode-button-text="选集"
    container-height="100vh"
    @next-video="nextVideo"
    @prev-video="prevVideo"
    @toggle-like="handleToggleLike"
    @toggle-star="handleToggleStar"
    @toggle-episode-selector="toggleEpisodeSelector"
    @comment-submitted="handleCommentSubmitted"
    @select-episode="onSelectEpisode"
  >
    <!-- 返回按钮 -->
    <template #back-button>
      <button
        @click="$router.back()"
        class="absolute top-4 left-4 z-50 text-white bg-black bg-opacity-50 p-2 rounded-full"
      >
        <i class="fas fa-arrow-left"></i>
      </button>
    </template>

    <!-- 剧集选择器 -->
    <template #extra-content>
      <div
        v-if="showEpisodeSelector"
        class="absolute inset-0 z-50 bg-black bg-opacity-90"
        @click="closeEpisodeSelector"
      >
        <div class="absolute inset-0 flex items-center justify-center" @click.stop>
          <div class="bg-gray-900 rounded-lg p-6 w-11/12 max-w-md max-h-[80vh] flex flex-col">
            <div class="flex items-center justify-between mb-4 flex-shrink-0">
              <h3 class="text-white text-lg font-medium">选择剧集</h3>
              <button @click="closeEpisodeSelector" class="text-gray-400 hover:text-white">
                <i class="fas fa-times"></i>
              </button>
            </div>

            <div class="episode-scroll-container flex-1" ref="episodeScrollRef">
              <div
                v-for="(episode, index) in videos"
                :key="episode.id"
                @click="selectEpisode(index, episode)"
                :class="[
                  'flex items-center p-3 rounded-lg mb-2 cursor-pointer transition-colors',
                  currentEpisodeIndex === index
                    ? 'bg-orange-400 text-white'
                    : 'bg-gray-800 text-gray-300 hover:bg-gray-700'
                ]"
              >
                <div class="w-12 h-16 bg-gray-600 rounded mr-3 flex items-center justify-center">
                  <span class="text-xs">{{ index + 1 }}</span>
                </div>
                <div class="flex-1 min-w-0">
                  <h4 class="font-medium truncate">{{ episode.title }}</h4>
                  <p class="text-sm opacity-75 truncate">{{ episode.description }}</p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </template>
  </VideoPlayer>
</template>

<script setup>
import { reqDramaAllEpisodes, toggleEpisodeLike, toggleEpisodeFavorite, reqSubmitEpisodeComment } from '@/apis/video'
import VideoPlayer from '@/components/VideoPlayer.vue'

const route = useRoute()
const router = useRouter()
const dramaId = route.params.dramaId || ''
const episodeIndex = route.params.episodeIndex || 0

// 视频相关状态
const currentVideoIndex = ref(0)
const videos = ref([])
const currentVideo = ref({})
const currentEpisodeIndex = ref(0)

// 剧集选择器相关
const showEpisodeSelector = ref(false)
const episodeScrollRef = ref(null)

// 视频切换状态
const isVideoSwitching = ref(false)

/**
 * 加载视频数据
 */
const loadVideos = async () => {
  try {
    console.log('加载视频数据，剧集ID:', dramaId)
    const response = await reqDramaAllEpisodes(dramaId)
    const { episodes } = response.data

    console.log('加载的视频数据:', episodes)

    if (episodes && episodes.length > 0) {
      videos.value = episodes
      updateCurrentVideo()
    }
  } catch (error) {
    console.error('加载视频失败:', error)
  }
}

/**
 * 更新当前视频
 */
const updateCurrentVideo = () => {
  if (videos.value.length > 0 && currentVideoIndex.value < videos.value.length) {
    const video = videos.value[currentVideoIndex.value]
    currentVideo.value = video
  }
}

const onSelectEpisode = (data) => {
  const video = videos.value[data.index]
  currentVideo.value = video

  currentVideoIndex.value = data.index
  currentEpisodeIndex.value = data.index
}

/**
 * 下一个视频
 */
const nextVideo = () => {
  resetRouter()
  if (isVideoSwitching.value) return

  if (currentVideoIndex.value < videos.value.length - 1) {
    isVideoSwitching.value = true
    currentVideoIndex.value++
    currentEpisodeIndex.value++
    updateCurrentVideo()

    setTimeout(() => {
      isVideoSwitching.value = false
    }, 500)
  }
}

/**
 * 上一个视频
 */
const prevVideo = () => {
  resetRouter()
  if (isVideoSwitching.value) return

  if (currentVideoIndex.value > 0) {
    isVideoSwitching.value = true
    currentVideoIndex.value--
    currentEpisodeIndex.value--
    updateCurrentVideo()

    setTimeout(() => {
      isVideoSwitching.value = false
    }, 500)
  }
}

/**
 * 初始化剧集选择器滚动
 */
const initEpisodeScroll = () => {
  nextTick(() => {
    if (episodeScrollRef.value) {
      episodeScrollRef.value.style.overflowY = 'auto'
      episodeScrollRef.value.style.webkitOverflowScrolling = 'touch'

      let startY = 0
      const handleTouchStart = (e) => {
        startY = e.touches[0].clientY
      }

      const handleTouchMove = (e) => {
        const currentY = e.touches[0].clientY
        const deltaY = startY - currentY

        if (Math.abs(deltaY) > 10) {
          e.stopPropagation()
        }
      }

      episodeScrollRef.value.addEventListener('touchstart', handleTouchStart, { passive: true })
      episodeScrollRef.value.addEventListener('touchmove', handleTouchMove, { passive: false })
    }
  })
}

/**
 * 切换剧集选择器
 */
const toggleEpisodeSelector = () => {
  resetRouter()
  showEpisodeSelector.value = !showEpisodeSelector.value
  if (showEpisodeSelector.value) {
    initEpisodeScroll()
  }
}

const closeEpisodeSelector = () => {
  showEpisodeSelector.value = false
}

/**
 * 选择剧集
 */
const selectEpisode = async (index, _) => {
  if (index === currentVideoIndex.value) {
    showEpisodeSelector.value = false
    return
  }

  console.log('~~~~~~~~选择剧集:', index)

  currentEpisodeIndex.value = Number(index)
  currentVideoIndex.value = Number(index)

  updateCurrentVideo()
  showEpisodeSelector.value = false

  // const episodeIndex = route.params.episodeIndex
  // currentEpisodeIndex.value = episodeIndex
}

// 监听路由的变化
watch(
  () => route.params.episodeIndex,
  (episodeIndex) => {
    if (episodeIndex !== undefined) {
      selectEpisode(episodeIndex)
    }
  },
  { immediate: true, deep: true }
)

const resetRouter = () => {
  if (episodeIndex === undefined) return

  router.replace({ name: 'Player', params: { dramaId } })
}

/**
 * 处理点赞
 */
const handleToggleLike = async (data) => {
  console.log('点赞状态:', data)

  // 集数ID
  const episodeId = data.currentVideo.cid
  // 点赞或取消点赞
  const action = data.isLiked ? 'like' : 'unlike'

  // 调用点赞接口
  const res = await toggleEpisodeLike(episodeId, action)
  console.log('点赞接口响应:', res)
}

/**
 * 处理收藏
 */
const handleToggleStar = async (data) => {
  console.log('收藏状态:', data)

  // 集数ID
  const episodeId = data.currentVideo.cid
  // 收藏或取消收藏
  const action = data.isLiked ? 'favorite' : 'unfavorite'

  // 调用收藏接口
  const res = await toggleEpisodeFavorite(episodeId, action)
  console.log('收藏接口响应:', res)
}

/**
 * 评论提交后处理
 */
const handleCommentSubmitted = async (data) => {
  console.log('评论已提交:', data)

  const episodeId = data.video.cid

  const res = await reqSubmitEpisodeComment(episodeId, {
    content: data.comment.content
  })

  console.log('评论提交接口响应:', res)
}

// 生命周期
onMounted(() => {
  loadVideos()
})
</script>

<style scoped>
.video-container {
  position: relative;
  width: 100vw;
  height: 100vh;
  background: #000;
  overflow: hidden;
}

.video-player {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  z-index: 10;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 3px solid rgba(255, 255, 255, 0.3);
  border-top: 3px solid #fff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

.loading-text {
  color: #fff;
  margin-top: 16px;
  font-size: 14px;
}

.play-icon-overlay {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
  width: 80px;
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 15;
}

.play-icon-overlay i {
  color: #fff;
  font-size: 32px;
}

.action-buttons {
  position: absolute;
  right: 16px;
  bottom: 120px;
  display: flex;
  flex-direction: column;
  gap: 24px;
  z-index: 10;
}

.action-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
}

.action-icon {
  font-size: 32px;
  color: #fff;
  margin-bottom: 4px;
  transition: all 0.3s ease;
}

.action-icon.liked {
  color: #ff4757;
}

.action-icon.starred {
  color: #ffa502;
}

.action-count {
  color: #fff;
  font-size: 12px;
  text-align: center;
}

.video-info {
  position: absolute;
  left: 16px;
  bottom: 20px;
  right: 80px;
  color: #fff;
  z-index: 10;
}

.author-info {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.author-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 12px;
  border: 2px solid #fff;
}

.author-name {
  font-weight: bold;
  font-size: 16px;
}

.video-description {
  font-size: 14px;
  line-height: 1.4;
  margin-bottom: 8px;
  max-height: 60px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
}

.video-meta {
  display: flex;
  gap: 16px;
  font-size: 12px;
  color: rgba(255, 255, 255, 0.8);
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

/* 触摸优化 */
.video-container {
  touch-action: pan-y;
  user-select: none;
}
</style>
